<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>订单管理</el-breadcrumb-item>
            <el-breadcrumb-item>订单列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card class="order-card">
            <el-row :gutter="20" class="search-row">
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                    <el-input v-model="queryInfo.query" class="search-input" placeholder="请输入订单编号或昵称"
                        prefix-icon="Search">
                        <template #append>
                            <el-button :icon="Search" type="primary" @click="handleSearch" />
                        </template>
                    </el-input>
                </el-col>
                <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="total-info">
                    <el-tag type="info" effect="dark">总订单数: {{ total }}</el-tag>
                </el-col> -->
            </el-row>

            <el-table :data="orders" border stripe highlight-current-row class="order-table" :max-height="tableMaxHeight">
                <el-table-column type="index" label="#" width="50" align="center"></el-table-column>
                <el-table-column prop="order_number" label="订单编号" width="130" align="center">
                    <template #default="scope">
                        <el-tag effect="plain" type="info">#{{ scope.row.order_number }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户昵称" width="120" align="center">
                    <template #default="scope">
                        <div class="user-info">
                            <el-avatar :size="30" :icon="UserFilled"></el-avatar>
                            <span class="username">{{ scope.row.username }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="total_price" label="订单价格" width="89" align="center">
                    <template #default="scope">
                        <span class="price-tag">¥{{ scope.row.total_price }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="订单状态" width="100" align="center">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)" effect="light">
                            <span v-if="scope.row.status === 'Processing'">待付款</span>
                            <span v-else-if="scope.row.status === 'Paid'">已付款</span>
                            <span v-else-if="scope.row.status === 'Confirmed'">已确认</span>
                            <span v-else-if="scope.row.status === 'Shipped'">已发货</span>
                            <span v-else-if="scope.row.status === 'In_Transit'">运输中</span>
                            <span v-else-if="scope.row.status === 'Delivered'">已送达</span>
                            <span v-else-if="scope.row.status === 'Completed'">已完成</span>
                            <span v-else-if="scope.row.status === 'Return'">退货/退款中</span>
                            <span v-else-if="scope.row.status === 'Closed'">已关闭</span>
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="is_send" label="是否发货" width="90" align="center">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status === 'In_Transit' || scope.row.status === 'Delivered' || scope.row.status === 'Completed' || scope.row.is_send === true" type="success" effect="dark">
                            已发货
                        </el-tag>
                        <el-tag v-else type="warning" effect="dark">
                            未发货
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="consignee_addr" label="收货地址" width="190" align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="created_at" label="下单时间" width="180" align="center">
                    <template #default="scope">
                        <div class="time-info">
                            <span>{{ scope.row.created_at }}</span>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="250" align="center" fixed="right">
                    <template #default="scope">
                        <div class="action-buttons">
                            <el-button 
                                v-if="hasPermission('修改地址功能')" 
                                type="primary" 
                                @click="showBox(scope.row)" 
                                size="small" 
                                class="action-btn"
                            >
                                <el-icon>
                                    <Edit />
                                </el-icon> 修改地址
                            </el-button>
                            <el-button 
                                v-if="hasPermission('商品发货功能') && !scope.row.is_send && (scope.row.status !== 'In_Transit' && scope.row.status !== 'Delivered' && scope.row.status !== 'Completed' && scope.row.status !== 'Closed')" 
                                type="success" 
                                @click="handleShipOrder(scope.row)" 
                                size="small"
                                :loading="scope.row.shipping"
                                class="action-btn"
                            >
                                <el-icon>
                                    <Truck />
                                </el-icon> 商品发货
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
                    :page-sizes="[1, 8, 20, 50]" :page-size="queryInfo.pagesize" :current-page="queryInfo.pagenum"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 修改地址对话框 -->
        <el-dialog v-model="dialogVisible" title="修改地址" width="500" @close="addressDialogClosed">
            <el-form :model="addressForm" :rules="addressRules" ref="addressFormRef" label-width="100px" label-position="right">
                <el-form-item label="省市区/县" prop="address1">
                    <el-cascader v-model="addressForm.address1" :options="cityData" :props="cascaderProps"
                        placeholder="请选择省市区/县" />
                </el-form-item>
                <el-form-item label="详细地址" prop="address2">
                    <el-input v-model="addressForm.address2" placeholder="请输入详细地址" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveAddress" :loading="saveLoading">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>




    </div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { onMounted, ref, watch, onUnmounted, onBeforeUnmount } from "vue"
import axios from "@/utils/http"
import cityData from "./citydata"
import { Search, UserFilled, Check, Clock, Calendar, View, Edit, Wallet, ShoppingCart, Truck, Box, CircleCheck, WarningFilled, CloseBold, ArrowRight } from '@element-plus/icons-vue'

// 权限检查函数
const hasPermission = (permission) => {
    const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}')
    console.log('当前用户信息:', userInfo)
    const permissions = userInfo.functions || []
    console.log('当前用户权限:', permissions, '检查权限:', permission)
    return permissions.includes(permission)
}
const queryInfo = ref({
    query: '',
    pagenum: 1,
    pagesize: 10,
})
// const cityData = cityData
const total = ref(0)
const orders = ref([])
const dialogVisible = ref(false)
const saveLoading = ref(false)
const currentOrderId = ref('')
const tableMaxHeight = ref(window.innerHeight - 300)

// 监听窗口大小变化
// 提取resize事件处理函数
const handleResize = () => {
    tableMaxHeight.value = window.innerHeight - 300
}

const resizeListener = ref(null)

onMounted(() => {
    resizeListener.value = handleResize
    window.addEventListener('resize', resizeListener.value)
})

onBeforeUnmount(() => {
    if (resizeListener.value) {
        window.removeEventListener('resize', resizeListener.value)
        resizeListener.value = null
    }
    // 确保所有异步操作都已取消
    saveLoading.value = false
})

// 地址表单数据
const addressForm = ref({
    address1: [],
    address2: '',
    receiver: '',
})

// 地址表单验证规则
const addressRules = {
    address1: [
        { required: true, message: '请选择省市区/县', trigger: 'blur' },
    ],
    address2: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
    ],
}

// 地址表单引用
const addressFormRef = ref(null)

const getOrderList = async () => {
    console.log('请求参数：', {
        page: queryInfo.value.pagenum,
        page_size: queryInfo.value.pagesize,
        query: queryInfo.value.query
    });

    const { data: res } = await axios.get('/api/order/list/', {
        params: {
            page: queryInfo.value.pagenum,
            page_size: queryInfo.value.pagesize,
            query: queryInfo.value.query
        }
    })

    if (res.code !== 200) {
        return ElMessage.error(res.message)
    }
    console.log("获取到的订单列表数据", res);
    orders.value = res.data.orders
    total.value = res.data.total
}
const showBox = (order) => {
    // 设置当前订单ID
    currentOrderId.value = order.id
    
    // 如果订单有地址信息，则填充表单
    if (order.address_info) {
        addressForm.value.receiver = order.address_info.receiver || ''
        addressForm.value.phone = order.address_info.phone || ''
        addressForm.value.address = order.address_info.address || ''
    } else {
        // 重置表单
        addressForm.value = {
            receiver: '',
            phone: '',
            address: ''
        }
    }
    
    dialogVisible.value = true
    console.log('显示修改地址弹窗，当前订单ID:', currentOrderId.value);
}
// 根据订单状态返回对应的图标
const getStatusIcon = (status) => {
    switch (status) {
        case 'Processing': return 'ShoppingCart';
        case 'Paid': return 'Wallet';
        case 'Confirmed': return 'Check';
        case 'Shipped': return 'Box';
        case 'In_Transit': return 'Truck';
        case 'Delivered': return 'CircleCheck';
        case 'Completed': return 'CircleCheck';
        case 'Return': return 'WarningFilled';
        case 'Closed': return 'CloseBold';
        default: return 'Info';
    }
}

// 根据订单状态返回对应的标签类型
const getStatusType = (status) => {
    switch (status) {
        case 'Processing': return 'info';
        case 'Paid': return 'success';
        case 'Confirmed': return 'warning';
        case 'Shipped': return 'primary';
        case 'In_Transit': return 'primary';
        case 'Delivered': return 'success';
        case 'Completed': return 'warning';
        case 'Return': return 'danger';
        case 'Closed': return 'info';
        default: return 'info';
    }
}

// 处理分页大小变化
const handleSizeChange = (newSize) => {
    console.log("分页大小变化", newSize);
    queryInfo.value.pagesize = newSize
    getOrderList()
}

// 添加防抖函数
const debounce = (fn, delay) => {
    let timer = null
    return function (...args) {
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}
// 优化搜索处理
const handleSearch = debounce(() => {
    queryInfo.value.pagenum = 1
    getOrderList()
}, 300)

// 修改 watch，使用防抖处理
watch(() => queryInfo.value.query, debounce((newVal) => {
    queryInfo.value.pagenum = 1
    getOrderList()
}, 300))
// 处理页码变化
const handleCurrentChange = (newPage) => {
    console.log("页码变化", newPage);
    queryInfo.value.pagenum = newPage
    getOrderList()
}
// 保存地址信息
const saveAddress = async () => {
    // 表单验证
    if (!addressFormRef.value) return
    
    try {
        // 表单验证
        await addressFormRef.value.validate()
        
        // 显示加载状态
        saveLoading.value = true
        
        // 构建完整地址字符串
        const fullAddress = addressForm.value.address1.join(' ') + ' ' + addressForm.value.address2
        
        // 发送请求到后端
        const { data: res } = await axios.put(`/api/orders_address/${currentOrderId.value}/`, {
            address: fullAddress
        })
        
        if (res.code !== 200) {
            return ElMessage.error(res.message || '修改地址失败')
        }
        
        // 提示成功
        ElMessage.success('地址修改成功')
        
        // 关闭对话框
        dialogVisible.value = false
        
        // 刷新订单列表
        getOrderList()
    } catch (error) {
        console.error('保存地址时出错:', error)
        ElMessage.error('表单数据不完整或有误')
    } finally {
        // 无论成功失败，都关闭加载状态
        saveLoading.value = false
    }
}
const addressDialogClosed = () => {
  if (addressFormRef.value) {
    addressFormRef.value.resetFields()
  }
}

// 处理发货操作
const handleShipOrder = async (order) => {
    try {
        // 设置当前订单的发货状态为加载中
        order.shipping = true
        
        // 发送请求到后端
        const { data: res } = await axios.post(`/member/order/${order.id}`, {
            orderState: 'In_Transit'
        })
        
        if (res.code !== 200) {
            return ElMessage.error(res.message || '发货失败')
        }
        
        // 提示成功
        ElMessage.success('发货成功')
        
        // 刷新订单列表
        getOrderList()
    } catch (error) {
        console.error('发货操作失败:', error)
        ElMessage.error('发货失败，请重试')
    } finally {
        // 取消加载状态
        order.shipping = false
    }
}

onMounted(() => {
    // 获取订单列表
    getOrderList()
})
</script>
<style scoped>
.order-card {
    margin-top: 15px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-row {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.search-input {
    width: 100%;
    max-width: 600px;
}

.total-info {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 10px;
}

@media screen and (max-width: 768px) {
    .total-info {
        justify-content: flex-start;
        margin-top: 15px;
    }
}

.order-table {
    margin-bottom: 20px;
    width: 100%;
}

.user-info {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    flex-wrap: nowrap;
}

.username {
    margin-left: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.price-tag {
    font-weight: bold;
    color: #ff6b6b;
}

.status-icon {
    margin-right: 5px;
    vertical-align: middle;
}

.time-info {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
}

.action-buttons {
    display: flex;
    flex-direction: column;
    gap: 8px;
    justify-content: flex-start;
}

.action-btn {
    margin: 2px 0;
    white-space: nowrap;
}

@media (min-width: 768px) {
    .action-buttons {
        flex-direction: row;
        flex-wrap: wrap;
        justify-content: flex-start;
    }
    .action-btn {
        margin: 0 2px;
    }
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    flex-wrap: wrap;
    gap: 10px;
}

.el-cascader {
    width: 100%;
}

@media screen and (max-width: 576px) {
    .el-pagination {
        justify-content: center;
        flex-wrap: wrap;
    }
}
</style>